package cn.edu.zime.tjh.iotapp.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ImageUtils {
    private static final String TAG = "ImageUtils";

    /**
     * 压缩图片
     * @param context 上下文
     * @param imageUri 图片URI
     * @param isAvatar 是否为头像
     * @return 压缩后的图片文件
     */
    public static File compressImage(Context context, Uri imageUri, boolean isAvatar) throws IOException {
        // 创建临时文件
        File compressedFile = createTempImageFile(context, isAvatar ? "avatar_" : "img_");
        
        // 从URI读取原始图片
        InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
        Bitmap originalBitmap = BitmapFactory.decodeStream(inputStream);
        inputStream.close();
        
        // 获取原始图片尺寸
        int originalWidth = originalBitmap.getWidth();
        int originalHeight = originalBitmap.getHeight();
        
        Log.d(TAG, "原始图片尺寸: " + originalWidth + "x" + originalHeight);
        
        // 目标文件大小和尺寸设置
        long maxFileSize = isAvatar ? 512 * 1024 : 2 * 1024 * 1024; // 头像512KB，普通图片2MB
        int targetSize = isAvatar ? 300 : 800; // 头像300px，普通图片800px
        
        // 计算缩放比例
        float scaleFactor;
        
        if (isAvatar) {
            // 头像处理：保持正方形
            int size = Math.min(originalWidth, originalHeight);
            scaleFactor = (float) targetSize / size;
        } else {
            // 普通图片处理
            scaleFactor = 1.0f;
            File imageFile = new File(imageUri.getPath());
            if (imageFile.exists() && imageFile.length() > maxFileSize) {
                scaleFactor = (float) Math.sqrt((double) maxFileSize / imageFile.length() * 0.8);
            }
        }
        
        // 计算目标尺寸
        int targetWidth, targetHeight;
        
        if (isAvatar) {
            // 头像处理为正方形
            targetWidth = targetHeight = targetSize;
            
            // 对原图进行裁剪，取中心正方形区域
            int size = Math.min(originalWidth, originalHeight);
            int offsetX = (originalWidth - size) / 2;
            int offsetY = (originalHeight - size) / 2;
            
            // 创建中心裁剪的位图
            Bitmap croppedBitmap = Bitmap.createBitmap(
                    originalBitmap, offsetX, offsetY, size, size);
            
            // 缩放到目标尺寸
            originalBitmap = Bitmap.createScaledBitmap(croppedBitmap, targetSize, targetSize, true);
            
            // 回收中间位图
            if (croppedBitmap != originalBitmap) {
                croppedBitmap.recycle();
            }
        } else {
            // 普通图片保持原始比例
            targetWidth = (int) (originalWidth * scaleFactor);
            targetHeight = (int) (originalHeight * scaleFactor);
            
            // 确保尺寸不小于最小值
            targetWidth = Math.max(targetWidth, 800);
            targetHeight = Math.max(targetHeight, 800);
            
            // 缩放图片
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, targetWidth, targetHeight, true);
            originalBitmap = scaledBitmap;
        }
        
        Log.d(TAG, "缩放后图片尺寸: " + targetWidth + "x" + targetHeight);
        
        // 压缩质量
        int quality = isAvatar ? 90 : 85; // 头像质量稍高
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        originalBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        
        // 如果压缩后仍然太大，继续降低质量
        while (outputStream.toByteArray().length > maxFileSize && quality > 30) {
            outputStream.reset();
            quality -= 10;
            Log.d(TAG, "调整压缩质量至: " + quality);
            originalBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        }
        
        // 写入文件
        FileOutputStream fos = new FileOutputStream(compressedFile);
        fos.write(outputStream.toByteArray());
        fos.flush();
        fos.close();
        
        // 回收位图资源
        originalBitmap.recycle();
        
        return compressedFile;
    }
    
    /**
     * 创建临时图片文件
     */
    public static File createTempImageFile(Context context, String prefix) throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = prefix + timeStamp + "_";
        File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        
        return File.createTempFile(imageFileName, ".jpg", storageDir);
    }
    
    /**
     * 将Bitmap转换为Base64字符串
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return android.util.Base64.encodeToString(byteArray, android.util.Base64.DEFAULT);
    }
} 